package util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;

/**
 * @author oahner
 * @create 2022-04-27 19:25
 */
public class SnowIdUtil {

    Logger logger= LoggerFactory.getLogger(this.getClass());

    private static long workerId=0;

    private static long datacenterId=1;

    public long getWorkerId() {
        return workerId;
    }

    public void setWorkerId(long workerId) {
        this.workerId = workerId;
    }

    public long getDatacenterId() {
        return datacenterId;
    }

    public void setDatacenterId(long datacenterId) {
        this.datacenterId = datacenterId;
    }

    public Snowflake getSnowflake() {
        return snowflake;
    }

    public void setSnowflake(Snowflake snowflake) {
        this.snowflake = snowflake;
    }

    private static Snowflake snowflake= IdUtil.createSnowflake(workerId,datacenterId);

    @PostConstruct
    public void init(){
        try {
            workerId= NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            logger.info("====workerId===="+workerId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("error workerId");
            workerId=NetUtil.getLocalhostStr().hashCode();
        }
    }

    public static synchronized long getSnowflakeId(){
        return snowflake.nextId();
    }

    public synchronized long getSsnowflakeId(long workerId,long datacenterId){
        Snowflake snowflake= IdUtil.createSnowflake(workerId,datacenterId);
        return snowflake.nextId();
    }
}
